#include "mystdio.h"

mFile* myfopen(const char* filename,const char* mode)
{
    int fd = -1;
    if(filename)
    {
        if(strcmp(mode,"w") == 0)
        {
            fd = open(filename,O_WRONLY | O_CREAT | O_RDONLY,0666);
        }
        else if(strcmp(mode,"r") == 0)
        {
            fd = open(filename,O_RDONLY);
        }
        else if(strcmp(mode,"a") == 0)
        {
            fd = open(filename,O_WRONLY | O_CREAT | O_APPEND,0666);
        }
        if(fd < 0) return NULL;
        mFile* fp = (mFile*)malloc(sizeof(mFile));
        if(fp == NULL) 
        {
            close(fd);
            return NULL;
        }
        fp->fileno = fd;
        fp->flag = FLUSH_LINE;
        fp->size = 0;
        fp->cap = SIZE;
        memset(fp->outbuffer,0,sizeof(fp->outbuffer));
        return fp;
    }
    else 
    {
        return NULL;
    }
}
int myfwrite(const void* ptr,size_t size,size_t  num,mFile* stream)
{
    if(ptr)
    {
        memcpy(stream->outbuffer + stream->size,ptr,size * num);
        stream->size += size * num;
        if(stream->flag == FLUSH_LINE && stream->size > 0  && stream->outbuffer[stream->size - 1] == '\n')
        {
            myfflush(stream);
        }
        return size * num;
    }
    else
    {
        return 0;
    }
}
void myfflush(mFile* stream)
{
    if(stream->size > 0)
    {
        //写到文件内核缓冲区中
        write(stream->fileno,stream->outbuffer,stream->size);
        //文件内核缓冲区数据刷新
        fsync(stream->fileno);
        stream->size = 0;

    }
}
void myfclose(mFile* stream)
{
    if(stream->size > 0)
    myfflush(stream);
    close(stream->fileno);
}
